//
//  SelectDriverVC.m
//  NtoccShipper
//
//  Created by mac on 2019/12/6.
//  Copyright © 2019 zhuchongjin. All rights reserved.
//

#import "SelectDriverVC.h"
#import "DriverListModel.h"
//#import "DriverListCell.h"
#import "SelectDriverListCell.h"
// 承运分组
#import "AppectGroupCell.h"
#import "AppeptNewGroupVC.h"
#import "GroupInfoVC.h"
#import "AppectCroupModel.h"
#import "UINavigationController+FDFullscreenPopGesture.h"

@interface SelectDriverVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) CJTableView *tableView;
@property (nonatomic,strong) AppectGroupCell *appectGroupCell;
@property (nonatomic,strong) NSMutableArray *modelArray;
@property (nonatomic,strong) CJTextField *fieldSerach;
@property (nonatomic,strong) NSString *refreshType; //刷新
@property (nonatomic,readwrite) int page;
@property (weak, nonatomic) IBOutlet UIButton *btnSave;
@property (nonatomic,strong) UISegmentedControl *segment; //分段控制
@property (nonatomic, assign)BOOL isSelectDriver;// 是否是司机
@property (nonatomic,strong) FlexFrameView *header;
@end

@implementation SelectDriverVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    [self setTitleName:CJLString(@"用车类型")];
    [self setBackLeftButton:@""];
    [self selectSendGoodsType];
    self.btnSave.backgroundColor = [UIColor cjMainColor];
    self.isSelectDriver = NO;
    [self createTopView];
    self.appectGroupCell = [[AppectGroupCell alloc]initWithFlex:nil reuseIdentifier:nil];
    [self.view addSubview:self.tableView];
    
    WS(ws);
    self.tableView.placeHolderView = [[KKTableViewNoDataView alloc] initWithFrame:self.tableView.bounds image:[UIImage imageNamed:@"no_data"] viewClick:^{
           [ws.tableView.mj_header beginRefreshing];
    }];
    [self initData];
    [self loadData];
    self.fd_interactivePopDisabled = YES;
}

- (void)backClick:(UIButton *)sender{
    
    if (self.isSelectDriver) {

        NSMutableArray *list = [[NSMutableArray alloc]init];
        DriverListModel *mod = [[DriverListModel alloc]init];
        mod.name = @"";
        mod.partyCode = @"";
        [list addObject:mod];
        
        if (self.blockSeletArr) {
            self.blockSeletArr(list);
        }

    }else{
        
        NSDictionary *dic = @{@"name":@"",
                              @"code":@""
        };
        if (self.blockDic) {
            self.blockDic(dic);
        }
    }

    [self pop];
}


- (void)initData{
    self.modelArray = [[NSMutableArray alloc]init];
    self.page = 1;
}
- (void)selectSendGoodsType{
   
    NSArray *array = [NSArray arrayWithObjects:@"承运分组",@"司机",nil];
    self.segment = [[UISegmentedControl alloc]initWithItems:array];
    self.segment.frame = CGRectMake((SCREEN_WIDTH-LW(180))/2, LW(5) + kStatusBarHeight, LW(180), LW(30));
    [self.segment addTarget:self action:@selector(changeType:) forControlEvents:UIControlEventValueChanged];
    [self.image addSubview:self.segment];
    //

   if (DeviceSystemVersion.doubleValue > 13) {
       UIColor *tintColor = [UIColor cjMainColor];
       UIImage *tintColorImage = [UIImage imageWithColor:[UIColor cjMainColor]];
       // Must set the background image for normal to something (even clear) else the rest won't work
       [self.segment setBackgroundImage:[UIImage imageWithColor:self.segment.backgroundColor ? self.segment.backgroundColor : [UIColor clearColor]] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
       [self.segment setBackgroundImage:tintColorImage forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
       [self.segment setBackgroundImage:[UIImage imageWithColor:[tintColor colorWithAlphaComponent:0.2]] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
       [self.segment setBackgroundImage:tintColorImage forState:UIControlStateSelected|UIControlStateSelected barMetrics:UIBarMetricsDefault];
       [self.segment setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor cjWhiteColor], NSFontAttributeName: [UIFont cjTitleFont14]} forState:UIControlStateSelected];
       [self.segment setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor cjMainColor], NSFontAttributeName: [UIFont cjTitleFont14]} forState:UIControlStateNormal];
       [self.segment setDividerImage:tintColorImage forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
       self.segment.layer.borderWidth = 0.5;
       self.segment.layer.borderColor = [tintColor CGColor];
       self.segment.selectedSegmentIndex = 0;
   }else{
       self.segment.tintColor = [UIColor cjMainColor];
   }
   self.segment.selectedSegmentIndex = 0;
}

//不同分段
-(void)changeType:(UISegmentedControl *)sender{
    
    if (sender.selectedSegmentIndex == 0) {
        self.isSelectDriver = NO;
        [self.btnSave setTitle:@"新增承运分组" forState:UIControlStateNormal];
        self.header.hidden = YES;
        self.tableView.frame = CGRectMake(0, kTopHeight +  CJTableToTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight  - self.btnSave.height - CJTableToTopHeight);
        
    }else{
        self.isSelectDriver = YES;
        [self.btnSave setTitle:@"确定" forState:UIControlStateNormal];
        self.header.hidden = NO;
        self.tableView.frame = CGRectMake(0, kTopHeight +  CJTableToTopHeight + self.header.height, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight  - self.btnSave.height - CJTableToTopHeight - self.header.height);
    }
    [self.modelArray removeAllObjects];
    [self.tableView reloadData];
    [self.tableView.mj_header beginRefreshing];
    
}

- (void)createTopView{
    //    WS(ws);
    CGRect rcFrame = CGRectMake(0, kTopHeight, [[UIScreen mainScreen] bounds].size.width, 0);
    self.header = [[FlexFrameView alloc] initWithFlex:@"SelectDiverSearchTopView" Frame:rcFrame Owner:self];
    self.header.flexibleHeight = YES;
    self.header.hidden = YES;
    [self.header layoutIfNeeded];
    [self.view addSubview:self.header];
    
}

- (void)btnSerachRouteView{
    
    [self.tableView.mj_header beginRefreshing];
}

- (IBAction)btnSaveAction:(UIButton *)sender {
    WS(ws);
    if (self.isSelectDriver) {
//        DriverListModel *model = self.modelArray[indexPath.row];
        __block NSMutableArray *list = [[NSMutableArray alloc]init];
        [self.modelArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            DriverListModel *mod = (DriverListModel *)obj;
            if (mod.selected) {
                [list addObject:mod];
            }
        }];
        
        if (list.count > 0) {
            if (self.blockSeletArr) {
                self.blockSeletArr(list);
            }
           
        }else{
//
//            model.name;
//        strCode = model.partyCode;
            DriverListModel *mod = [[DriverListModel alloc]init];
            mod.name = @"";
            mod.partyCode = @"";
            [list addObject:mod];
            
            if (self.blockSeletArr) {
                self.blockSeletArr(list);
            }
        }
        
        [self pop];
        
    }else{

        AppeptNewGroupVC *vc = [[AppeptNewGroupVC alloc]init];
        vc.blockSuccess = ^(id anyObject) {
            [ws.tableView.mj_header beginRefreshing];
        };
        [self pushVc:vc];
    }
}


/// <#Description#>
- (void)loadData{

    NSString *strURL = @"";
    NSDictionary *dicPar;
    
    if (self.isSelectDriver) {
        strURL = CJStringWithFormat(@"%@/ntocc-basic-api/driver/driverList",CJBaseUrl);
        dicPar = @{
            @"pageNum":CJStringWithFormat(@"%d",self.page),
            @"pageSize":@"10",
            @"authStatus":@"3",
            @"isFreeze":@"0",
            @"workStatus":@"1",
            @"driverType":@"6",  //展示加入车队的独立司机
            @"searchInfo":[CJRegular getIsStrEmpty:self.fieldSerach.text] ? @"":self.fieldSerach.text,
            @"branchCodeExt":[CJControl getBranchCode]
        };
    }else{
        
        strURL = CJStringWithFormat(@"%@/ntocc-basic-api/vehicleTeam",CJBaseUrl);
        dicPar = @{
            @"pageNum":CJStringWithFormat(@"%d",self.page),
            @"pageSize":@"10",
            @"acceptType":@"1"
        };
    }

    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
        
        DLog(@"++++++++%@",responseObject);
        NSArray *list = responseObject[@"records"];
        NSString *total = CJStringWithFormat(@"%@",responseObject[@"total"]);
//        if (list.count > 0) {
            //            #import "CommonRouteModel.h"
            if ([ws.refreshType isEqualToString:@"down"]) {
                [ws.modelArray removeAllObjects];
            }
            
            if (ws.isSelectDriver) {
                [list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                   NSError *error;
                    DriverListModel *model = [[DriverListModel alloc]initWithDictionary:obj error:&error];
                    model.selected = NO;
                    [ws.modelArray addObject:model];
                }];
            }else{
                NSError * error ;
                NSArray *arr = [AppectCroupModel arrayOfModelsFromDictionaries:list error:&error];
                [ws.modelArray addObjectsFromArray:arr];
            }
            
            [ws.tableView.mj_header endRefreshing];
            [ws.tableView.mj_footer endRefreshing];
            
            if (ws.modelArray.count == total.intValue) {
                [ws.tableView.mj_footer endRefreshingWithNoMoreData];
            }
//            [ws createTopView];
            
//        }else{
//
//            [ws.tableView.mj_header endRefreshing];
//            [ws.tableView.mj_footer endRefreshingWithNoMoreData];
//        }
//
        [ws.tableView reloadData];
        
    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        
    }];
}

- (void)downRefresh{
    self.refreshType = @"down";
    self.page = 1;
    [self loadData];
}

- (void)upRefresh{
    self.refreshType = @"up";
    self.page ++;
    [self loadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (self.isSelectDriver) {
   
        static NSString *identifier = @"SelectDriverListCell";
        SelectDriverListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[SelectDriverListCell alloc] initWithFlex:[CJControl getUIWithNew] ? @"SelectDriverListCellNew":@"SelectDriverListCell" reuseIdentifier:identifier];
           cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }

        DriverListModel *model = self.modelArray[indexPath.row];
        [cell setCellInfiWithModel:model];
        WS(ws);
        cell.blockSelect = ^(id anyObject) {
            if (model.selected) {
                model.selected = NO;
            }else{
                model.selected = YES;
            }
            [ws.tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationFade];
        };
        return cell;
        
    }else{
        
        static NSString *identifier = @"AppectGroupCell";
        AppectGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[AppectGroupCell alloc] initWithFlex:nil reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }

        AppectCroupModel *model = self.modelArray[indexPath.row];
        [cell setCellInfoWithModel:model];

        WS(ws);
        cell.blockDelect = ^(id anyObject) {
            [ws delectAppectGroupWithCode:model];
        };
        cell.blockChange = ^(id anyObject) {
            [ws changeAppectGroupWithCode:model.code withTitle:model.name];
        };
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (self.isSelectDriver) {
        DriverListModel *model = self.modelArray[indexPath.row];

        if (model.selected) {
            model.selected = NO;
        }else{
            model.selected = YES;
        }
        [self.tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationFade];
    }else{
        
        AppectCroupModel *mod = self.modelArray[indexPath.row];
        NSDictionary *dic = @{@"name":mod.name,
                              @"code":mod.code
        };
        if (self.blockDic) {
            self.blockDic(dic);
        }
        [self pop];
    }
}

- (void)changeAppectGroupWithCode:(NSString *)code withTitle:(NSString *)title{
    GroupInfoVC *vc = [[GroupInfoVC alloc]init];
    vc.strCode = code;
    vc.strTitle = title;
    [self pushVc:vc];
}

- (void)delectAppectGroupWithCode:(AppectCroupModel *)model{

    NSString *strUrl = CJStringWithFormat(@"%@/ntocc-basic-api/vehicleTeam/batchDelTeam",CJBaseUrl);
    NSDictionary *dicPra = @{@"teamCodes":model.code,
                             };
    WS(ws);
    CJAlertView *alert = [[CJAlertView alloc]initWithTitle:@"删除提醒" strContent:[CJPromptInfo getHintPromptType:@"删除" withNextStep:model.name] ClickOnSure:^(NSString * _Nonnull strSure) {
        
       [[HDNetworking sharedHDNetworking] DELETE:strUrl parameters:dicPra success:^(id  _Nonnull responseObject) {
           
            [ws.tableView.mj_header beginRefreshing];

       } failure:^(NSError * _Nonnull error) {
           DLog(@"++++++++%@",error);
       }];
    } ClickOnCancle:^(NSString * _Nonnull strCancle) {
       
    }];
    
    alert.center = KEYWINDOW.center;
    WLAlertView * alertView = [[WLAlertView alloc]init];
    alertView.containerView = alert;
    alertView.isTouchOtherUndissmiss=YES;
    [alertView show];
}

- (void)addAppectGoud:(CJButton *)sender{
    
    WS(ws);
    AppeptNewGroupVC *vc = [[AppeptNewGroupVC alloc]init];
    vc.blockSuccess = ^(id anyObject) {
        [ws.tableView.mj_header beginRefreshing];
    };
    [self pushVc:vc];
}

- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, kTopHeight +  CJTableToTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight  - self.btnSave.height - CJTableToTopHeight),UITableViewStylePlain)
        .tbDelegate(self)
        .tbDataSource(self)
        .tbSetOther(YES)
        .tbEstimatedRowHeight(YES)
        .tbMjHeadFooter(YES)
        ;
        WS(ws);
        _tableView.blockMjHeader = ^(BOOL isheader) {
            
            if (isheader) {
                [ws downRefresh];
            } else {
                [ws upRefresh];
            }
        };
    }
    return _tableView;
}

@end
